﻿/*************************************************************************
 * Created by OhZee Creative, LLC
 * 2013
 * This code is licensed under Microsoft Public License (Ms-PL)
 * http://opensource.org/licenses/ms-pl
 * http://ozframework.codeplex.com/
 *************************************************************************/

namespace OhZeeCreative.Sound.Windows8
{
    using System;
    using System.Collections.Generic;
    using Windows.UI.Xaml.Controls;

	public class SoundChannelCollection
	{
		private object lockObject = new object();
		private SoundChannel[] sounds;

		public SoundChannelCollection(int numberOfChannels)
		{
			this.sounds = new SoundChannel[numberOfChannels];

			for (int index = 0; index < this.sounds.Length; index++)
			{
				this.sounds[index] = new SoundChannel();
			}
		}

		public IEnumerable<SoundChannel> Items
		{
			get { return this.sounds; }
		}

		public void SetParent(Panel newParent)
		{
			lock (lockObject)
			{
				foreach (SoundChannel sound in this.sounds)
				{
					Panel currentParent = sound.MediaElement.Parent as Panel;  // We can only remove it from a Panel
					if (currentParent != null)
					{
						currentParent.Children.Remove(sound.MediaElement);
					}
					newParent.Children.Add(sound.MediaElement);
				}
			}
		}

		public SoundChannel GetFreeChannel()
		{
			foreach (SoundChannel sound in this.sounds)
			{
				if (!sound.IsBusy)
				{
					return sound;
				}
			}
			return null;
		}

		public SoundChannel MakeFreeChannel()
		{
			int oldestIndex = -1;
			DateTime oldest = DateTime.MinValue;
			for (int index = 0; index < this.sounds.Length; index++)
			{
				if (index == 0)
				{
					oldest = this.sounds[index].StartTime;
					continue;
				}

				if (this.sounds[index].StartTime < oldest)
				{
					oldest = this.sounds[index].StartTime;
					oldestIndex = index;
				}
			}

			if (oldestIndex >= 0)
			{

				SoundChannel channel = this.sounds[oldestIndex];
				channel.Reset();
				return channel;
			}

			return null;
		}
	}
}
